<?php session_start() ?>
<!DOCTYPE html>
<html>
<head>
	<title>Edit Property</title>
	<meta charset="utf-8">
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
	<link rel="stylesheet" href="stylesheet.css">
	<link rel="preconnect" href="https://fonts.gstatic.com">
	<link href="https://fonts.googleapis.com/css2?family=Josefin+Sans:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;1,100;1,200;1,300;1,400;1,500;1,600;1,700&display=swap" rel="stylesheet">
	<!-- jQuery library -->
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

	<!-- Popper JS -->
	<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>

	<!-- Latest compiled JavaScript -->
	<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>

</head>

<body> 

<!-- Sell property form. It has two parts. 
	First part uploads multiple images to server directory and creates array of file names.
	Second part (after submit button) checks array and if any names adds them to DB with all other info.
	It has to have restrictions on file sizes, types and quantities.
	Also in real life this requires captcha, session control, passwords so on
	Also all file names have to be unique to prevent conflicts in directory/ DB
	Also if user adds images and no other info those images have to be deleted later on-->

 <?php

require 'header.php';
require_once 'connect.php';

$city = $suburb = $street_name = $street_num = $bedrooms_num = $price = $description = "";
$city_err = $suburb_err = $street_name_err = $street_num_err = "";
$image_err = $bedrooms_num_err = $price_err = $description_err = $status = $statusMsg  = "";

// sanitize string

function sanitize_string($string, $min='', $max='')
{
  $string = preg_replace("/[^0-9]/", "", $string);
  $len = strlen($string);
  if((($min != '') && ($len < $min)) || (($max != '') && ($len > $max))){
  	return FALSE;
  }
  else{
  		return $string;
  }
}



if ( isset($_GET['edit'])){

    $property_id = $_GET['edit'];

    $sql = "SELECT properties.id, bedrooms, price, description, addresses.city, addresses.suburb, addresses.street_name, addresses.street_number FROM properties
    INNER JOIN addresses ON addresses.property_id = properties.id
    WHERE properties.id = ".$property_id;


	$result = $conn->query($sql);			 
//echo print_r ($result);

	if($result->num_rows == 1){
		$row = $result->fetch_assoc();
		//$row ($bedrooms, $price, $description, $city, $suburb, $street_name, $street_number);
		$bedrooms = $row['bedrooms'];
		$price = $row['price'];
		$description = $row['description'];
		$city = $row['city'];
		$suburb = $row['suburb'];
		$street_name = $row['street_name'];
		$street_number = $row['street_number'];
		$_SESSION['property_id'] = $row['id'];

		//echo $_SESSION['property_id'];

		// echo "$bedrooms.$street_name.$street_number";
	}
}

if(isset($_POST["submit"])){

	// checking if everything is filled in
	// also all fields which require some numbers, 
	// better make integers in DB so it easier for search later on


	

	if(empty(trim($_POST["city"]))){

		$city_err = "Please provide city name |";
	}
	else{
		$city = trim($_POST["city"]);
	}

	if(empty(trim($_POST["suburb"]))){

		$suburb_err = "Please provide name of suburb |";
	}
	else{
		$suburb = trim($_POST["suburb"]);
	}

	if(empty(trim($_POST["street_name"]))){

		$street_name_err = "Please provide street name |";
	}
	else{
		$street_name = trim($_POST["street_name"]);
	}

	if(empty(trim($_POST["street_num"]))){
		$street_num_err = "Please provide street number |";
	}
	else{
	
		$street_number = trim($_POST["street_num"]);
		$street_number = sanitize_string($street_number, 0,100000) ? $street_number : FALSE;
		// $street_num = is_numeric($street_num ) ? $street_num : FALSE;
		if (!$street_number) {
			echo("no street number "); 
		}else {
			// echo($street_num."<br>");//////////////echoing result 4 checking
			}	
	}

	if(empty(trim($_POST["bedrooms_num"]))){
		$bedrooms_num_err = "Please provide number of bedrooms |";
	}
	else{
		// To validate form data (string) as an integer ctype_digit() can be used.
		// It returns TRUE if every character in the string text is a decimal digit, FALSE otherwise.
		//Reference: http://php.net/manual/en/function.ctype-digit.php

		if(ctype_digit($_POST["bedrooms_num"])){

//		INTVAL Returns the int value of var, using the specified base for the conversion (the default is base 10). 
			$bedrooms = intval(trim($_POST["bedrooms_num"]));

			// echo($bedrooms_num);/////////////////////echoing result 4 error checking

		}else{
			$bedrooms_num_err = "Please use numbers only |";
		}		
	}

	if (empty(trim($_POST["price"]))) {

		$price_err = "Please provide asking price |";
	} 
	else {

		if(ctype_digit($_POST["price"])){

			$price = intval(trim($_POST["price"]));	

			// echo "<br>$price";	////////////////////	echoing result 4 error checking
		}
		else{
			$price_err = "Please use numbers only |";
		}		
	}

	if (empty(trim($_POST["description"]))) {
		$description_err = "Please provide description |";
	} 
	else {
		$description = trim($_POST["description"]);
	}

	//if no errors, adding everything to DB:

	if(empty($image_err) && empty($city_err) && empty($suburb_err) && empty($street_name_err) && empty($street_num_err) && empty($bedrooms_num_err) && empty($price_err) && empty($description_err)){


		$sql = "UPDATE properties SET bedrooms = ?, price = ?, description = ? WHERE properties.id = ?";

		$propertyId = $_SESSION['property_id'];

		$stmt = $conn->prepare($sql);
		$stmt->bind_param('iisi', $bedrooms, $price, $description, $_SESSION['property_id']);
		
		$bedrooms = $_POST['bedrooms_num'];
		$price = $_POST['price'];
		$description = $_POST['description'];

		if ( !($stmt-> execute())){
			echo "error in first stmt with properties table";}



		$sql = "UPDATE addresses SET city = ?, suburb = ?, street_name = ?, street_number = ? WHERE addresses.property_id = ?";

		$city = $_POST['city'];
		$suburb = $_POST['suburb'];
		$street_name = $_POST['street_name'];
		$street_number = $_POST['street_num'];
		$propertyId = $_SESSION['property_id'];


		$stmt1 = $conn->prepare($sql);

		$stmt1->bind_param('sssii', $city, $suburb, $street_name, $street_number, $propertyId);


		if ( !($stmt1-> execute())){
			echo "error in second stmt with properties table";} 


			if($stmt->execute()){
				echo "Your property info has been successfully changed!! <br>";
 		 	}



			  // Debuger
		// $sql = "SELECT city, suburb, street_name, street_number, bedrooms, price, description FROM adresses 
		// INNER JOIN properties ON properties.id = adresses.property_id
		// WHERE adresses.property_id = ".$_SESSION['property_id'];

		// $result = $conn->query($sql);			 

		// if ($result->num_rows > 0) {
		// 	// output data of each row
		// 	while($row = $result->fetch_assoc()) {
		// 	  echo $row["city"] . $row["suburb"]. $row["street_name"] . $row["street_number"].$row['bedrooms'].$row['price'].$row['description']. "<br>";
		// 	}
		//   } else {
		// 	echo "0 results";
		//   }
		


		//echo print_r ($stmt);




	
}
}
?>



<div class="edit-form-wrapper">
	<div>
		<h1>Edit Listing</h1>
		<p id="h3-edit-page">You can edit any field. All fields must be populated.</p>
	</div>
	<form id="edit-form" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">	
		<div class="input-group">	
			<div class="edit-fields-wrapper fields-wrapper form-group input-group-prepend">
				<input class="fields" type="text" name="city" class="form-control" placeholder="City" value="<?php echo $city; ?>">
				
			</div>
			<div class="edit-fields-wrapper fields-wrapper form-group">
				<input class="fields" type="text" name="suburb" class="form-control" placeholder="Suburb" value="<?php echo $suburb; ?>">
			</div>
			<span class="help-block"><?php echo $city_err; ?> </span><span class="help-block"><?php echo $suburb_err; ?> </span>
		</div>
		<br>
		<div class="input-group">
			<div class="edit-fields-wrapper fields-wrapper form-group input-group-prepend">
				<input class="fields" type="text" name="street_name" class="form-control" placeholder="Street name" value="<?php echo $street_name; ?>">
			</div>
			<div class="edit-fields-wrapper fields-wrapper form-group">
				<input class="fields" type="text" name="street_num" class="form-control" placeholder="Street number" value="<?php echo $street_number; ?>">
					
			</div>
			<span class="help-block"><?php echo $street_name_err; ?> </span> <span class="help-block"><?php echo $street_num_err; ?></span>
		</div>
		<br>
		<div class="input-group">
			<div class="edit-fields-wrapper fields-wrapper input-group-prepend form-group <?php echo (!empty($bedrooms_num_err))?'has error':''?>">
				<input class="fields" type="text" name="bedrooms_num" class="form-control" placeholder="" value="<?php echo $bedrooms; ?>">
			</div>
			<div class="edit-fields-wrapper fields-wrapper form-group <?php echo (!empty($price_err))?'has error':''?>">
				<input class="fields" type="text" name="price" class="form-control" placeholder="" value="<?php echo $price; ?>">	
			</div>
				<span class="help-block"><?php echo $bedrooms_num_err; ?> </span><span class="help-block"><?php echo $price_err; ?></span>	
		</div>
		<br>
		<div class="edit-fields-wrapper form-group p-desc-wrapper<?php echo (!empty($description_err))?'has error':''?>">
			<textarea class="form-control p-desc-field" rows="5" name="description" placeholder=""><?php echo $description; ?></textarea>
		</div>
		<span class="help-block"><?php echo $description_err; ?></span>
		<div class="edit-fields-wrapper form-group">
			<div class="input-group btn-group">
				<input type="submit" name="submit" class="btn-max btn-size" value="Edit Listing">
			</div>	
		</div>
	</form> 
</div>	


</body>
</html>